import api from "@/utils/api";
import { Toast } from "antd-mobile";
export default {
  namespace: 'cart',
  state: {
    items: localStorage.getItem("items")
        ?
        JSON.parse(localStorage.getItem("items") as string)
        :
        []
    ,
    number: localStorage.getItem("number")||0,
    price:  localStorage.getItem("price")||0
  },
  reducers: {
    initCart(state: any, action:any){
      state.items = action.data.items;
      state.number = action.data.number;
      state.price = action.data.price;
      
      localStorage.setItem('items', JSON.stringify(state.items));
      localStorage.setItem('number', state.number);
      localStorage.setItem('price', state.price);
      return {
        ...state
      }
    }
  },
  effects: {
    // 加入购物车 dispatch  {type: 'cart/addCart', params: {}}
    *addCart(action: any, {call, put}){
      const res = yield call(api.addCart, action.params)
      if (res.data.code === 0) {
        yield  put({
          type: 'initCart',
          data: res.data.data
        })
        Toast.show('加入购物车成功')
      }
      
    },
    // 获取购物车数据
    *getCartInfo(action: any, {call, put}){
      const res = yield call(api.getCartInfo);
      if (res.data.code === 0) {
        yield  put({
          type: 'initCart',
          data: res.data.data
        })
      }
    },
    // 修改商品购买数量
    *changeNum(action: any, {call, put}){
      const res = yield call(api.changeCartItemNum, action.params)
      if (res.data.code === 0) {
        yield  put({
          type: 'initCart',
          data: res.data.data
        })
        Toast.show('修改数量成功')
      }
    },
    // 删除商品
    *remoItem(action: any, {call, put}){
      const res = yield call(api.removeCartItem, action.params)
      if (res.data.code === 0) {
        yield  put({
          type: 'initCart',
          data: res.data.data
        })
        Toast.show('删除商品成功')
      }
      if (res.data.code === 700) {
        yield  put({
          type: 'initCart',
          data: {
            items: [],
            price: 0,
            number: 0
          }
        })
        Toast.show('删除商品成功')
      }
    },
    // 修改商品选中状态
    *changeItemSelectedStatus(action: any, {call, put}){
      const res = yield call(api.changeItemSelectStatus, action.params)
      if (res.data.code === 0) {
        yield  put({
          type: 'initCart',
          data: res.data.data
        })
      }
    },
  },
};
        